package vn.edu.uit.service.fetchers;

import java.util.ArrayList;

import org.json.JSONObject;

import vn.edu.uit.hotelbooking.JsonParse.HotelSearchResultParser;
import vn.edu.uit.hotelbooking.model.Hotel;
import vn.edu.uit.service.UITAPIContant;
import vn.edu.uit.service.UITHttpRequest;
import vn.edu.uit.service.UITHttpRequest.RequestMethod;
import vn.edu.uit.service.UITService;
import android.location.Location;
import android.util.Log;

public class HotelSearchResultFetcher {
    private static UITHttpRequest httpRequest;
    private static final String LOG_TAG = "HotelSearchResultFetcher";
    
    /**
     * The method to get the list of hotel that match searching's conditions
     * @param destination the destination to search
     * @param location the location of user
     * @return If success, return an Arraylist<Hotel> contains the hotels. If failed, return null. 
     */
    public static ArrayList<Hotel> getHotelSearchResult(String destination, Location location) {
        UITService.REQUEST_SUCCESS = false;
        httpRequest=new UITHttpRequest(UITAPIContant.API_REST_DOMAIN_URL+UITAPIContant.Api_Functions.GET_HOTEL_SEARCH);
        httpRequest.addParam(UITService.TAG_AUTHENTICATE, UITService.TOKEN);
        httpRequest.addParam("destination", destination);
        if (destination.equals("My location")) {
            httpRequest.addParam("lat", String.valueOf(location.getLatitude()));
            httpRequest.addParam("long", String.valueOf(location.getLongitude()));
        }
        try {
            JSONObject object = httpRequest.doExecute(RequestMethod.POST);
            Log.d("JSON", object.toString());
            if(object.getInt(UITService.TAG_ERROR)==0) {       //request was successful, return a hotel arraylist
                UITService.REQUEST_SUCCESS = true;
                return HotelSearchResultParser.getHotelFromJson(object.getJSONArray(UITService.TAG_DATA)); 
                
            } else {                                //request was failed, return null
                UITService.REQUEST_SUCCESS = false;
                UITService.MSG = object.getString(UITService.TAG_MSG);
                return null;
            }   
            
        } catch (Exception e) {
            // TODO Auto-generated catch block
            Log.e(LOG_TAG, e.getMessage());
        }
        return null;
    }   
}
